<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Article extends MY_Controller {

	public function __construct(){
		parent::__construct();
	}

	public function category($catid = 0, $page = 1){
		$catid = (int)$catid;
		
		$_time = gmdate('Y-m-d H:i:s', time() + 7*3600);
		$category = $this->db->where(array('id' => $catid, 'publish' => 1))->from('article_category')->get()->row_array();
		if(!isset($category) || count($category) == 0) $this->my_string->php_redirect(ITQ_BASE_URL);
		$author = $this->db->select('id, username, fullname, google_author')->where(array('id' => $category['userid_created']))->from('user')->get()->row_array();		
		if(!isset($author) || count($author) == 0) $this->my_string->php_redirect(ITQ_BASE_URL);
		$this->my_frontend->lang($category['lang']);
		$_lang = $this->session->userdata('_lang');
		$config = $this->my_frontend->pagination();
		$config['first_url'] = $this->my_frontend->canonical($category['route'], $category['alias'], $category['id'], '68', FALSE).ITQ_URL_SUFFIX;
		$config['base_url'] = $this->my_frontend->canonical($category['route'], $category['alias'], $category['id'], '68', FALSE).'/trang-';
		if($category['rgt'] - $category['rgt'] == 1){
			$config['total_rows'] = $this->db->from('article_item')->where(array('lang' => $_lang, 'publish' => 1, 'parentid' => $catid, 'created <= ' => $_time))->count_all_results();
		} else{
			$_children = $this->my_nestedset->children('article_category', array('lft >=' => $category['lft'], 'rgt <=' => $category['rgt'], ));
			$config['total_rows'] = $this->db->from('article_item')->where(array('lang' => $_lang, 'publish' => 1, 'created <= ' => $_time))->where_in('parentid', $_children)->count_all_results();
		}
		$_totalpage = ceil($config['total_rows']/$config['per_page']);
		$page = ($page <= 1)?1:$page; $page = ($page > $_totalpage)?$_totalpage:$page;
		$config['cur_page'] = $page;
		if($config['total_rows'] > 0){
			$this->pagination->initialize($config); 
			$data['data']['pagination'] = $this->pagination->create_links();
			if($category['rgt'] - $category['rgt'] == 1){
				$data['data']['_listdata'] = $this->db->select('id, title, alias, route, parentid, image, description, created')->from('article_item')->where(array('lang' => $_lang, 'parentid' => $catid, 'publish' => 1, 'created <= ' => $_time))->limit($config['per_page'], ($page - 1) * $config['per_page'])->order_by('order desc, created desc')->get()->result_array();
			} else{
				$data['data']['_listdata'] = $this->db->select('id, title, alias, route, parentid, image, description, created')->from('article_item')->where(array('lang' => $_lang, 'publish' => 1, 'created <= ' => $_time))->where_in('parentid', $_children)->limit($config['per_page'], ($page - 1) * $config['per_page'])->order_by('order desc, created desc')->get()->result_array();
			}
		}
		$data['data']['_config'] = $config;
		$data['data']['_page'] = $page;
		$_seopage = ($page > 1)?' - Trang '.$page:'';
		$data['seo']['title'] = (!empty($category['meta_title'])?$category['meta_title']:$category['title']).$_seopage;
		$data['seo']['meta_keywords'] = $category['meta_keywords'];
		$data['seo']['meta_description'] = (!empty($category['meta_description'])?$category['meta_description']:strip_tags($category['description'])).$_seopage;
		if($page > 1){
			$data['seo']['canonical'] = $this->my_frontend->canonical($category['route'], $category['alias'], $category['id'], '68', FALSE).'/trang-'.$page.ITQ_URL_SUFFIX;
		}
		else{
			$data['seo']['canonical'] = $this->my_frontend->canonical($category['route'], $category['alias'], $category['id'], '68');
		}
		$fullurl = current(explode('?', $this->my_string->fullurl()));
		if($fullurl != $data['seo']['canonical']) $this->my_string->php_redirect($data['seo']['canonical']);
		$data['data']['_category'] = $category;
		$data['data']['_author'] = $author;
		if($category['rgt'] - $category['lft'] > 1 && $category['level'] == 1){
			$data['data']['_children'] = $this->db->select('id, title, route, alias')->from('article_category')->where(array('parentid' => $category['id'], 'publish' => 1))->get()->result_array();
		}
		else if($category['level'] > 1){
			$data['data']['_children'] = $this->db->select('id, title, route, alias')->from('article_category')->where(array('parentid' => $category['parentid'], 'publish' => 1))->get()->result_array();
		}
		if($page == 2) $data['seo']['rel_prev'] = $config['first_url'];
		else if($page > 2) $data['seo']['rel_prev'] = $config['base_url'].($page-1).ITQ_URL_SUFFIX;
		if($page < $_totalpage) $data['seo']['rel_next'] = $config['base_url'].($page+1).ITQ_URL_SUFFIX;

		$data['data']['_active'] = $this->my_frontend->active($category['route'], $category['alias'], $category['id'], '68', FALSE);

		// View
		$_sql = 'SELECT `id`, `title`, `alias`, `route`, `parentid`, `image`, `description`, `created` FROM `'.ITQ_DB_PREFIX.'article_item` WHERE `lang` = ? AND `publish` = ? AND `created` <= ? ORDER BY `viewed` DESC LIMIT 0, 5';
		$_param = array($_lang, 1, $_time);
		$data['data']['_listview'] = $this->db->query($_sql, $_param)->result_array();
		
		$data['template'] = 'frontend/article/category';
		$this->load->view('frontend/layout/home', isset($data)?$data:NULL);
	}

	public function item($itemid = 0){
		$itemid = (int)$itemid;
		$_time = gmdate('Y-m-d H:i:s', time() + 7*3600);
		$item = $this->db->where(array('id' => $itemid, 'publish' => 1, 'created <= ' => $_time))->from('article_item')->get()->row_array();		
		if(!isset($item) || count($item) == 0) $this->my_string->php_redirect(ITQ_BASE_URL);
		$author = $this->db->select('id, username, fullname, google_author')->where(array('id' => $item['userid_created']))->from('user')->get()->row_array();		
		if(!isset($author) || count($author) == 0) $this->my_string->php_redirect(ITQ_BASE_URL);
		$category = $this->db->where(array('id' => $item['parentid'], 'publish' => 1))->from('article_category')->get()->row_array();		
		if(!isset($category) || count($category) == 0) $this->my_string->php_redirect(ITQ_BASE_URL);
		$this->my_frontend->lang($item['lang']);
		$_lang = $this->session->userdata('_lang');
		if($this->input->post('comment')){
			$_post = $this->input->post('data');
			$data['data']['_post'] = $_post;
			$this->form_validation->set_error_delimiters('<li>', '</li>');
			$this->form_validation->set_rules('data[fullname]', 'Họ và tên', 'trim|required');
			$this->form_validation->set_rules('data[email]', 'Email', 'trim|required|valid_email');
			$this->form_validation->set_rules('data[content]', 'Nội dung', 'trim|required');
			if($this->form_validation->run() == TRUE){
				$_post = $this->my_string->allow_post($_post, array('fullname', 'email', 'content'));
				$_post['created'] = gmdate('Y-m-d H:i:s', time() + 7*3600);
				$_post['param'] = 'article/item/'.$itemid;
				$this->db->insert('comment', $_post);
				$this->my_string->js_reload('Gửi phản hồi thành công!');
			}
		}
		$data['seo']['title'] = (!empty($item['meta_title'])?$item['meta_title']:$item['title']);
		$data['seo']['meta_keywords'] = $item['meta_keywords'];
		$data['seo']['meta_description'] = (!empty($item['meta_description'])?$item['meta_description']:strip_tags($item['description']));
		$data['seo']['canonical'] = $this->my_frontend->canonical($item['route'], $item['alias'], $item['id'], '88');
		$fullurl = current(explode('?', $this->my_string->fullurl()));
		if($fullurl != $data['seo']['canonical']) $this->my_string->php_redirect($data['seo']['canonical']);
		$data['data']['_comment'] = $this->db->from('comment')->where(array('param' => 'article/item/'.$itemid, 'publish' => 1))->order_by('id asc')->get()->result_array();
		$view_article_item = $this->session->userdata('view_article_item_'.$item['id']);
		if(!isset($view_article_item) || empty($view_article_item)){
			$this->session->set_userdata('view_article_item'.$item['id'], 'ok');
			$this->db->set('viewed', 'viewed + 1', FALSE)->where(array('id' => $item['id']))->update('article_item');
			$item['viewed']++;
		}
		$this->db->set('total_comment', count($data['data']['_comment']), FALSE)->where(array('id' => $item['id']))->update('article_item');
		$data['data']['_item'] = $item;
		$data['data']['_category'] = $category;
		$data['data']['_author'] = $author;
		if($category['rgt'] - $category['lft'] > 1 && $category['level'] == 1){
			$data['data']['_children'] = $this->db->select('id, title, route, alias')->from('article_category')->where(array('parentid' => $category['id'], 'publish' => 1))->get()->result_array();
		} else if($category['level'] > 1){
			$data['data']['_children'] = $this->db->select('id, title, route, alias')->from('article_category')->where(array('parentid' => $category['parentid'], 'publish' => 1))->get()->result_array();
		}

		if(!empty($item['tags'])){
			$tags = $this->my_tag->tags($item['tags']);
			if(isset($tags) && count($tags)){
				$field = '';
				$query_param = NULL;
				$count = count($tags); 
				foreach($tags as $key => $val){
					if($count == $key+1){
						$field = $field.'`tags` LIKE ?';
					}
					else{
						$field = $field.'`tags` LIKE ? OR ';
					}
					$query_param[] = '%'.$val.'%';
				}
				$query_param[] = $item['id'];
				$query_param[] = $_lang;
				$query_param[] = 1;
				$query_param[] = $_time;
				$query_sql = 'SELECT `id`, `title`, `alias`, `route`, `parentid`, `image`, `description`, `created` FROM '.ITQ_DB_PREFIX.'article_item WHERE ('.$field.') AND `id` != ? AND `lang` = ? AND `publish` = ? AND `created` <= ? ORDER BY `viewed` DESC LIMIT 0, 10';
				$data['data']['_related'] = $this->db->query($query_sql, $query_param)->result_array();
			}
		} else{
			$query_param[] = $item['id'];
			$query_param[] = $item['parentid'];
			$query_param[] = $_lang;
			$query_param[] = 1;
			$query_param[] = $_time;
			$query_sql = 'SELECT `id`, `title`, `alias`, `route`, `parentid`, `image`, `description`, `created` FROM '.ITQ_DB_PREFIX.'article_item WHERE `id` != ? AND `parentid` = ? AND `lang` = ? AND `publish` = ? AND `created` <= ? ORDER BY `viewed` DESC LIMIT 0, 3';
			$data['data']['_related'] = $this->db->query($query_sql, $query_param)->result_array();
		}
		
		$data['template'] = 'frontend/article/item';
		$this->load->view('frontend/layout/home', isset($data)?$data:NULL);
		
	}

	public function search($page = 1){
		$_time = gmdate('Y-m-d H:i:s', time() + 7*3600);
		$this->my_frontend->lang('vi');
		$_lang = $this->session->userdata('_lang');
		$keyword = $this->input->get('keyword');
		$config = $this->my_frontend->pagination();
		$config['suffix'] = $config['suffix'].'?keyword='.urlencode($keyword);
		$config['first_url'] = 'tim-kiem'.$config['suffix'];
		$config['base_url'] = 'tim-kiem/trang-';
		$_sql = 'SELECT * FROM '.ITQ_DB_PREFIX.'article_item WHERE `lang` = ? AND `publish` = ? AND `created` <= ? AND (`title` LIKE ? OR `description` LIKE ? OR `content` LIKE ?)';
		$_param = array($_lang, 1, $_time, '%'.$keyword.'%', '%'.$keyword.'%', '%'.$keyword.'%');
		$config['total_rows'] = $this->db->query($_sql, $_param)->num_rows();
		$_totalpage = ceil($config['total_rows']/$config['per_page']);
		$page = ($page <= 1)?1:$page; $page = ($page > $_totalpage)?$_totalpage:$page;
		$config['cur_page'] = $page;
		if($config['total_rows'] > 0){
			$this->pagination->initialize($config); 
			$data['data']['pagination'] = $this->pagination->create_links();
			$_sql = 'SELECT * FROM `'.ITQ_DB_PREFIX.'article_item` WHERE `lang` = ? AND `publish` = ? AND `created` <= ? AND (`title` LIKE ? OR `description` LIKE ? OR `content` LIKE ?) ORDER BY `created` DESC LIMIT '.(($page - 1) * $config['per_page']).', '.$config['per_page'];
			$_param = array($_lang, 1, $_time, '%'.$keyword.'%', '%'.$keyword.'%', '%'.$keyword.'%');
			$data['data']['_listdata'] = $this->db->query($_sql, $_param)->result_array();
		}
		$data['data']['_config'] = $config;
		$data['data']['_page'] = $page;
		$data['keyword'] = $keyword;
		$_seopage = ($page > 1)?' - Trang '.$page:'';
		$data['seo']['title'] = 'Kết quả tìm kiếm với từ khóa "'.$keyword.'"'.$_seopage;
		$data['seo']['meta_keywords'] = $keyword;
		$data['seo']['meta_description'] = 'Kết quả tìm kiếm với từ khóa "'.$keyword.'"'.$_seopage;
		if($page > 1){
			$data['seo']['canonical'] = ITQ_BASE_URL.'tim-kiem/trang-'.$page.$config['suffix'];
		}
		else{
			$data['seo']['canonical'] = ITQ_BASE_URL.'tim-kiem'.$config['suffix'];
		}
		$fullurl = current(explode('?', $this->my_string->fullurl())).substr($config['suffix'], 5);
		if($fullurl != $data['seo']['canonical']) $this->my_string->php_redirect($data['seo']['canonical']);
		if($page == 2) $data['seo']['rel_prev'] = ITQ_BASE_URL.$config['first_url'];
		else if($page > 2) $data['seo']['rel_prev'] = ITQ_BASE_URL.$config['base_url'].($page-1).$config['suffix'];
		if($page < $_totalpage) $data['seo']['rel_next'] = ITQ_BASE_URL.$config['base_url'].($page+1).$config['suffix'];

		// View
		$_sql = 'SELECT `id`, `title`, `alias`, `route`, `parentid`, `image`, `description`, `created` FROM `'.ITQ_DB_PREFIX.'article_item` WHERE `lang` = ? AND `publish` = ? AND `created` <= ? ORDER BY `viewed` DESC LIMIT 0, 5';
		$_param = array($_lang, 1, $_time);
		$data['data']['_listview'] = $this->db->query($_sql, $_param)->result_array();
		
		// Comment
		$_sql = 'SELECT `id`, `title`, `alias`, `route`, `parentid`, `image`, `description`, `created` FROM `'.ITQ_DB_PREFIX.'article_item` WHERE `lang` = ? AND `publish` = ? AND `created` <= ? ORDER BY `total_comment` DESC LIMIT 0, 5';
		$_param = array($_lang, 1, $_time);
		$data['data']['_listcomment'] = $this->db->query($_sql, $_param)->result_array();

		// Hot
		$_sql = 'SELECT `id`, `title`, `alias`, `route`, `parentid`, `image`, `description`, `created` FROM `'.ITQ_DB_PREFIX.'article_item` WHERE `lang` = ? AND `publish` = ? AND `hot` = ? AND `created` <= ? ORDER BY `created` DESC LIMIT 0, 5';
		$_param = array($_lang, 1, 1, $_time);
		$data['data']['_listhot'] = $this->db->query($_sql, $_param)->result_array();

		// Highlight
		$_sql = 'SELECT `id`, `title`, `alias`, `route`, `parentid`, `image`, `description`, `created` FROM `'.ITQ_DB_PREFIX.'article_item` WHERE `lang` = ? AND `publish` = ? AND `highlight` = ? AND `created` <= ? ORDER BY `created` DESC LIMIT 0, 5';
		$_param = array($_lang, 1, 1, $_time);
		$data['data']['_listhighlight'] = $this->db->query($_sql, $_param)->result_array();

		// Link
		$data['data']['_link'] = $this->db->select('id, title, url')->where(array('publish' => 1))->from('link')->get()->result_array();
		
		// Video
		$data['data']['_video'] = $this->db->select('id, title, code')->where(array('publish' => 1))->from('video')->get()->result_array();

		// Adv
		$_sql = 'SELECT `content` FROM `'.ITQ_DB_PREFIX.'adv` WHERE `lang` = ? AND `publish` = ? AND (`time_start` <= ? AND `time_end` >= ?) ORDER BY `order` ASC LIMIT 0, 10';
		$_param = array($_lang, 1, $_time, $_time);
		$data['data']['_listadv'] = $this->db->query($_sql, $_param)->result_array();

		$this->load->view('frontend/layout/search', isset($data)?$data:NULL);
	}
}
